<template>
  <Dialog
    :title="props.editId ? '修改':'新增'"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
    @handle-confirm="handleConfirm"
  >
    <el-form
      ref="formEl"
      v-loading="formLoading"
      :model="roleForm"
      :rules="rules"
      label-position="right"
      label-width="100px"
    >
      <el-form-item
        label="角色名称："
        prop="name"
      >
        <el-input
          v-model="roleForm.name"
          placeholder="请输入角色名称"
        />
      </el-form-item>
      <el-form-item
        label="默认："
        prop="isDefault"
      >
        <el-switch
          v-model="roleForm.isDefault"
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import Dialog from '@/components/Dialog/index.vue'
import type { IElForm } from '@/types/element-plus'
import { addRole, getRole, editRole } from '@/http/role'
import { ElMessage } from 'element-plus'
import { IRole } from '@/http/types/role'
const props = defineProps({
  editId: {
    type: String,
    default: ''
  }
})

interface EmitsType {
  (e: 'update:editId', value: number | null): void
  (e: 'success'): void
}
const emit = defineEmits<EmitsType>()

const data = {
  concurrencyStamp: '',
  extraProperties: {},
  id: '',
  isDefault: false,
  isPublic: false,
  isStatic: false,
  name: ''
}
const roleForm = ref<IRole>(data)

const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})

const formEl = ref<IElForm>()
const handleConfirm = async () => {
  try {
    await formEl.value?.validate()
    if (props.editId) {
      await editRole(props.editId, roleForm.value)
    } else {
      await addRole(roleForm.value)
    }
    emit('success')
    ElMessage.success('保存成功')
  } catch (err) {
  }
}
const formLoading = ref(false)
const handleDialogOpen = async () => {
  formLoading.value = true
  await loadRoles().finally(() => {
    formLoading.value = false
  })
}
const handleDialogClosed = () => {
  emit('update:editId', null)
  formEl.value?.resetFields() // 清除表单数据
}

const loadRoles = async () => {
  if (!props.editId) return
  roleForm.value = await getRole(props.editId)
}
</script>

<style scoped>

</style>
